import requests
from flask import Flask, render_template_string, request, jsonify
import json
import uuid
import urllib3
from requests.exceptions import ChunkedEncodingError

urllib3.disable_warnings()

app = Flask(__name__)

# 存储对话历史
conversations = {}

# TOKEN 文件路径
TOKEN_FILE_PATH = "token.txt"

def read_token_from_file():
    """
    从文件中读取 TOKEN
    """
    try:
        with open(TOKEN_FILE_PATH, "r") as file:
            token = file.read().strip()
        return token
    except Exception as e:
        print(f"读取 TOKEN 文件时发生错误: {e}")
        return None


# 调用Agent的函数
def call_agent(query, conversation_id=None):
    url = f"AGENT_URL"

    payload = json.dumps({"query": query}, ensure_ascii=False)

    # 获取 TOKEN
    token = read_token_from_file()
    if not token:
        print("TOKEN 无法加载，检测失败")
        return

    headers = {
        'Content-Type': 'application/json',
        'X-Auth-Token': token
    }

    try:
        response = requests.request("POST", url, headers=headers, data=payload.encode ("utf-8"), verify=False, stream=True)
        response.encoding = 'utf-8'
        print(response.status_code)
        print(response.text)

    except ChunkedEncodingError  as e:
        print(f"An error occurred: {e}")

    
    full_content = ""
    for line in response.iter_lines(decode_unicode=True):
        if line and line.startswith('data:'):
            data_str = line[len('data:'):]
            if data_str == '[DONE]':
                break
            try:
                data_json = json.loads(data_str)
                content = data_json.get('content', '')
                if content:
                    full_content += content
            except json.JSONDecodeError:
                pass
    response.close()
    return full_content


# 主页路由
@app.route('/')
def index():
    return render_template_string('''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>集成Agent的Web平台</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.4.0/css/all.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        neutral: '#F5F7FA',
                        dark: '#1D2129',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .chat-shadow {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            }
            .agent-avatar {
                transition: all 0.3s ease;
            }
            .agent-avatar:hover {
                transform: scale(1.05);
            }
            .chat-container {
                transform: translateX(100%);
                transition: transform 0.3s ease-out;
            }
            .chat-container.active {
                transform: translateX(0);
            }
            .message-bubble {
                max-width: 80%;
                animation: fadeIn 0.3s ease-in-out;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(10px); }
                to { opacity: 1; transform: translateY(0); }
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-dark">
    <!-- 主页面内容 -->
    <div class="min-h-screen flex flex-col">
        <!-- 顶部导航栏 -->
        <header class="bg-white shadow-sm">
            <div class="container mx-auto px-4 py-4 flex justify-between items-center">
                <div class="flex items-center space-x-2">
                    <i class="fa fa-cubes text-primary text-2xl"></i>
                    <h1 class="text-xl font-bold text-primary">OA办公平台</h1>
                </div>
                <nav class="hidden md:flex space-x-8">
                    <a href="#" class="text-gray-600 hover:text-primary transition-colors">首页</a>
                    <a href="#" class="text-gray-600 hover:text-primary transition-colors">功能</a>
                    <a href="#" class="text-gray-600 hover:text-primary transition-colors">帮助</a>
                    <a href="#" class="text-gray-600 hover:text-primary transition-colors">关于</a>
                </nav>
                <button class="md:hidden text-gray-600">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </header>

        <!-- 主要内容区 -->
        <main class="flex-grow container mx-auto px-4 py-8">
            <div class="bg-white rounded-xl shadow-sm p-6 mb-8">
                <h2 class="text-2xl font-bold mb-4">欢迎使用OA办公平台</h2>
                <p class="text-gray-600 mb-6">这是一个集成了智能Agent的示例Web平台。点击右下角的助手头像可以打开对话窗口，与智能Agent进行交互。</p>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div class="bg-neutral rounded-lg p-5 hover:shadow-md transition-shadow">
                        <div class="text-primary text-3xl mb-3">
                            <i class="fa fa-line-chart"></i>
                        </div>
                        <h3 class="font-semibold text-lg mb-2">数据分析</h3>
                        <p class="text-gray-600 text-sm">提供全面的数据分析功能，帮助您深入了解业务状况。</p>
                    </div>

                    <div class="bg-neutral rounded-lg p-5 hover:shadow-md transition-shadow">
                        <div class="text-primary text-3xl mb-3">
                            <i class="fa fa-cog"></i>
                        </div>
                        <h3 class="font-semibold text-lg mb-2">系统设置</h3>
                        <p class="text-gray-600 text-sm">自定义系统参数，满足您的个性化需求。</p>
                    </div>

                    <div class="bg-neutral rounded-lg p-5 hover:shadow-md transition-shadow">
                        <div class="text-primary text-3xl mb-3">
                            <i class="fa fa-users"></i>
                        </div>
                        <h3 class="font-semibold text-lg mb-2">用户管理</h3>
                        <p class="text-gray-600 text-sm">管理用户账户和权限，确保系统安全。</p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-sm p-6">
                <h3 class="text-xl font-bold mb-4">最近活动</h3>
                <div class="space-y-4">
                    <div class="flex items-start">
                        <div class="bg-primary/10 p-2 rounded-full mr-4">
                            <i class="far fa-file-alt text-primary"></i>
                        </div>
                        <div>
                            <p class="font-medium">报告已生成</p>
                            <p class="text-sm text-gray-500">销售月度报告已生成，点击查看详情</p>
                            <p class="text-xs text-gray-400 mt-1">10分钟前</p>
                        </div>
                    </div>

                    <div class="flex items-start">
                        <div class="bg-secondary/10 p-2 rounded-full mr-4">
                            <i class="fa fa-user-plus text-secondary"></i>
                        </div>
                        <div>
                            <p class="font-medium">新用户加入</p>
                            <p class="text-sm text-gray-500">3名新用户已注册并完成认证</p>
                            <p class="text-xs text-gray-400 mt-1">1小时前</p>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <!-- 页脚 -->
        <footer class="bg-white border-t mt-8 py-6">
            <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
                <p>© 2025 智能办公系统平台 版权所有</p>
            </div>
        </footer>
    </div>

    <!-- Agent对话部分 -->
    <div class="fixed bottom-8 right-8 z-50">
        <!-- 对话窗口 -->
        <div id="chatContainer" class="chat-container fixed bottom-8 right-8 w-80 md:w-96 bg-white rounded-xl chat-shadow h-[500px] flex flex-col">
            <!-- 对话窗口头部 -->
            <div class="bg-primary text-white p-4 rounded-t-xl flex justify-between items-center">
                <div class="flex items-center space-x-3">
                    <div class="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center">
                        <i class="fa fa-robot text-white"></i>
                    </div>
                    <h3 class="font-medium">智能办公助手</h3>
                </div>
                <button id="closeChat" class="text-white hover:text-gray-200 transition-colors">
                    <i class="fa fa-times"></i>
                </button>
            </div>

            <!-- 对话内容区域 -->
            <div id="chatMessages" class="flex-grow p-4 overflow-y-auto space-y-4">
                <div class="flex items-start">
                    <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center mr-2 flex-shrink-0">
                        <i class="fa fa-robot text-primary text-sm"></i>
                    </div>
                    <div class="message-bubble bg-primary/5 p-3 rounded-lg rounded-tl-none">
                        <p>你好！我是智能办公助手，有什么可以帮助你的吗？</p>
                    </div>
                </div>
            </div>

            <!-- 输入区域 -->
            <div class="border-t p-3">
                <form id="chatForm" class="flex space-x-2">
                    <input type="text" id="userInput" placeholder="输入你的问题..." 
                           class="flex-grow px-3 py-2 border border-gray-200 rounded-full focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    <button type="submit" class="bg-primary text-white w-10 h-10 rounded-full flex items-center justify-center hover:bg-primary/90 transition-colors">
                        <i class="far fa-paper-plane"></i>
                    </button>
                </form>
            </div>
        </div>

        <!-- 悬浮头像按钮 -->
        <button id="openChatBtn" class="agent-avatar bg-primary text-white w-14 h-14 rounded-full shadow-lg flex items-center justify-center">
            <i class="fa fa-comments text-xl"></i>
        </button>
    </div>

    <script>
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            const chatContainer = document.getElementById('chatContainer');
            const openChatBtn = document.getElementById('openChatBtn');
            const closeChatBtn = document.getElementById('closeChat');
            const chatForm = document.getElementById('chatForm');
            const userInput = document.getElementById('userInput');
            const chatMessages = document.getElementById('chatMessages');

            // 存储当前对话ID
            let conversationId = localStorage.getItem('agentConversationId');
            if (!conversationId) {
                conversationId = '{{ conversation_id }}';
                localStorage.setItem('agentConversationId', conversationId);
            }

            // 打开对话窗口
            openChatBtn.addEventListener('click', function() {
                chatContainer.classList.add('active');
                openChatBtn.classList.add('hidden');
            });

            // 关闭对话窗口
            closeChatBtn.addEventListener('click', function() {
                chatContainer.classList.remove('active');
                openChatBtn.classList.remove('hidden');
            });

            // 提交消息
            chatForm.addEventListener('submit', function(e) {
                e.preventDefault();
                const message = userInput.value.trim();
                if (message) {
                    // 添加用户消息到界面
                    addMessageToUI('user', message);

                    // 清空输入框
                    userInput.value = '';

                    // 发送消息到后端
                    sendMessageToAgent(message);
                }
            });

            // 添加消息到界面
            function addMessageToUI(sender, content) {
                const messageDiv = document.createElement('div');
                messageDiv.className = `flex items-start ${sender === 'user' ? 'justify-end' : ''}`;

                if (sender === 'user') {
                    messageDiv.innerHTML = `
                        <div class="message-bubble bg-primary text-white p-3 rounded-lg rounded-tr-none">
                            <p>${content}</p>
                        </div>
                    `;
                } else {
                    messageDiv.innerHTML = `
                        <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center mr-2 flex-shrink-0">
                            <i class="fa fa-robot text-primary text-sm"></i>
                        </div>
                        <div class="message-bubble bg-primary/5 p-3 rounded-lg rounded-tl-none">
                            <p>${content}</p>
                        </div>
                    `;
                }

                chatMessages.appendChild(messageDiv);
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }

            // 发送消息到Agent
            function sendMessageToAgent(message) {
                // 显示"正在输入"状态
                const typingDiv = document.createElement('div');
                typingDiv.id = 'typingIndicator';
                typingDiv.className = 'flex items-start';
                typingDiv.innerHTML = `
                    <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center mr-2 flex-shrink-0">
                        <i class="fa fa-robot text-primary text-sm"></i>
                    </div>
                    <div class="message-bubble bg-primary/5 p-3 rounded-lg rounded-tl-none">
                        <p class="text-gray-500">正在输入...</p>
                    </div>
                `;
                chatMessages.appendChild(typingDiv);
                chatMessages.scrollTop = chatMessages.scrollHeight;

                // 发送请求到后端
                fetch('/api/agent', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        message: message,
                        conversation_id: conversationId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    // 移除"正在输入"状态
                    document.getElementById('typingIndicator').remove();

                    // 添加Agent回复到界面
                    addMessageToUI('agent', data.response);
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('typingIndicator').remove();
                    addMessageToUI('agent', '抱歉，处理请求时出现错误，请稍后再试。');
                });
            }
        });
    </script>
</body>
</html>
    ''', conversation_id=str(uuid.uuid4()))


# 处理Agent请求的API
@app.route('/api/agent', methods=['POST'])
def agent_api():
    data = request.json
    message = data.get('message', '')
    conversation_id = data.get('conversation_id', '')

    if not conversation_id:
        conversation_id = str(uuid.uuid4())

    # 调用Agent获取响应
    response = call_agent(message, conversation_id)

    # 存储对话历史（实际项目中可使用数据库）
    if conversation_id not in conversations:
        conversations[conversation_id] = []
    conversations[conversation_id].append({
        'role': 'user',
        'content': message
    })
    conversations[conversation_id].append({
        'role': 'agent',
        'content': response
    })

    return jsonify({
        'response': response,
        'conversation_id': conversation_id
    })


if __name__ == '__main__':
    app.run(host="0.0.0.0",debug=True,port=8082)